package org.linjie.generate.core;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.Map;

/**
 * Freemarker 渲染器
 */
@Component("RendererFreemarkerImpl")
public class RendererFreemarkerImpl implements Renderer {

    private static Configuration cfg = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);

    private static Logger logger = LoggerFactory.getLogger(RendererFreemarkerImpl.class);

    @Autowired
    private Config config;

    //模版所在目录
    private File templateDir = null;

    @PostConstruct
    void init() {
        this.templateDir = new File(config.getTemplate());
        String basePath = config.getTemplate();
        try {
            cfg.setDirectoryForTemplateLoading(new File(basePath));
        } catch (IOException e) {
            logger.error("配置Freemarker 错误", e);
        }
    }

    @Override
    public void renderer(Map<String, Object> params) {
        String entityName = (String) params.get("entityName");
        String[] templateList = templateDir.list();
        Assert.notNull(templateList,"模板目录为空或不存在");

        for (String fileName : templateList) {
            String directory = fileName.substring(0, fileName.lastIndexOf('.'));
            renderer(params, entityName + fileName, config.getOutput() + "/" + directory, fileName);
        }
    }

    private void renderer(Map<String, Object> params, String newFilename, String output, String template) {
        Template temp = null;
        File file = new File(output);
        if (!file.exists()) {
            file.mkdirs();
        }
        try (Writer out = new OutputStreamWriter(new FileOutputStream(
                output + "/" + newFilename), "utf-8")) {
            temp = cfg.getTemplate(template);
            temp.process(params, out);
        } catch (Exception e) {
            logger.error("生成文件出错",e);
        }
    }
}
